package it.unibz.model;

import java.io.IOException;
import java.util.Iterator;

import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class Tweetproducer {
    protected DefaultHttpClient client;
    protected TweetFetcher consumer;

    public void createClient(String username, String password) {
        client = new DefaultHttpClient();
        client.getCredentialsProvider().setCredentials(
            new AuthScope("twitter.com", 80, AuthScope.ANY_REALM),
            new UsernamePasswordCredentials(username, password));
        //client.getParams().setAuthenticationPreemptive(true);
    }

    public void setConsumer(TweetFetcher consumer) {
        this.consumer = consumer;
    }

    public String execute(String since_id) throws TweetException {
        String id = null;
        String tmp;
        String url="http://twitter.com/statuses/friends_timeline.xml";
        if (since_id != null && since_id.length() > 0) {
           url+="?count=200&since_id=" + since_id;
        }
        else {
            url+="?count=200";
        }
        HttpGet get = new HttpGet(url);
        try {

            HttpResponse response = client.execute(get);
            HttpEntity entity = response.getEntity();

            SAXReader reader = new SAXReader();
            Document document = reader.read(entity.getContent());
            Element root = document.getRootElement();
            for (Iterator i = root.elementIterator(); i.hasNext(); ) {
                tmp = consumer.tweet((Element)i.next());
                if (id == null) id = tmp;
            }
        } catch (IOException e) {
            throw new TweetException(e);
        } catch (DocumentException e) {
            throw new TweetException(e);
        } finally {
        	client.getConnectionManager().shutdown();

        }
        return id;
    }
}

